package com.salton123.camera;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ConfigurationInfo;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Toast;


public class VirtualBackgroundRenderView extends GLSurfaceView {

    protected CameraRenderer mRenderer;
    private int textureId = -1;

    public VirtualBackgroundRenderView(Context context) {
        super(context);
        if (supportOpenGLESVersion(context)) {
            setEGLContextClientVersion(2);
            mRenderer = new CameraRenderer(context);
            setRenderer(mRenderer);
        } else {
            Toast.makeText(context, "此设备不支持OpenGL ES 2.0！", Toast.LENGTH_LONG).show();
        }
    }

    public void setBackgroundImage(int resId) {
        mRenderer.backgroundResId = resId;
        postInvalidate();
    }

    public VirtualBackgroundRenderView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        if (supportOpenGLESVersion(context)) {
            setEGLContextClientVersion(2);
        } else {
            Toast.makeText(context, "此设备不支持OpenGL ES 2.0！", Toast.LENGTH_LONG).show();
        }
        mRenderer = new CameraRenderer(context);
        setRenderer(mRenderer);
    }


    public void setRenderer(Context context, CameraV1 camera, boolean isPreviewStarted) {
        mRenderer.apply(context, camera, isPreviewStarted);
    }

    public boolean supportOpenGLESVersion(Context context) {
        final ActivityManager activityManager = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
//        Log.i("OpenGL ES version", "reqGlEsVersion: " + Integer.toHexString(configurationInfo.reqGlEsVersion) + ", GlEsVersion:" + configurationInfo.getGlEsVersion());
        return configurationInfo.reqGlEsVersion >= 0x20000;
    }

    public void deinit() {
        if (mRenderer != null) {
            mRenderer.deinit();
            mRenderer = null;
            textureId = -1;
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return mRenderer.onTouchEvent(event);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        deinit();
    }
}
